﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using MEC.WMS.FileMaintenance.SystemUser;
using MECPSDB.DatabaseSpecific;
using MECPSDB.EntityClasses;
using MECPSDB.HelperClasses;
using Pipo.AeExtensions;
using Pipo.LblGenExtensions;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace MEC.WMS
    {
    public partial class MainFrmLogin:DevExpress.XtraEditors.XtraForm
        {
        public string Cs;
        public string UserCode;
        public SystemuserEntity SystemUserEntity;
        public int UserId;

        

        public MainFrmLogin( )
            {
            InitializeComponent();
            if (Properties.Settings.Default.S_HideLoginAccountCharacters) checkEditalwayshide.Checked = true;
            //imageComboBoxEdit1.Properties.Items.Add(ELTV3Main.Properties.Settings.Default.ProdCs);
            //imageComboBoxEdit1.Properties.Items.Add(ELTV3Main.Properties.Settings.Default.TestCs);
            //imageComboBoxEdit1.Properties.Items.Add(ELTV3Main.Properties.Settings.Default.DevCS);
            imageComboBoxEdit1.SelectedItem = imageComboBoxEdit1.Properties.Items[0];
        }

        private void CheckEditalwayshideCheckedChanged(object sender,EventArgs e)
            {
            if (checkEditalwayshide.Checked){checkEdithidecharactersforusername.Checked = true;checkEdithidecharactersforusername.Enabled = false;}
            else{checkEdithidecharactersforusername.Enabled = true;}
            Properties.Settings.Default.Save();
            textEdit1.Focus();
        }

        private void CheckEdithidecharactersforusernameCheckedChanged(object sender,EventArgs e)
            {
            if (checkEdithidecharactersforusername.Checked) textEdit1.Properties.PasswordChar = Convert.ToChar("*");
            else textEdit1.Properties.PasswordChar =  (char) 0x0;
            textEdit1.Focus();
        }

        private void MainFrmLoginShown(object sender,EventArgs e){
            textEdit1.Focus();
        }

        private void BtnloginClick(object sender,EventArgs e)
            {
            if (textEdit1.Text.Length < 1){
                return;
            }
            if (textEdit2.Text.Length < 1){
                return;
            }
            if (imageComboBoxEdit1.SelectedItem == null){
                AskUser.PopupValidationError("Please select a server first.", "Log in");
                return;
            }
            BackgroundWorker b  = new BackgroundWorker();
            b.DoWork += OnBOnDoWork;
            b.RunWorkerCompleted += OnBOnRunWorkerCompleted;

            MethodLockUi(true);
            pictureEdit2.Image = Properties.Resources.facebookindicator;
            btnlogin.Enabled = false;
            btnlogin.Text = "Signing you in...";
            LoginParam loginParam = new LoginParam();
            loginParam.Cs = (string) imageComboBoxEdit1.EditValue;
            loginParam.Usercode = textEdit1.Text;
            loginParam.Password = textEdit2.Text;
            b.RunWorkerAsync(loginParam);

        }

        private struct LoginParam{
            public string Cs;
            public string Usercode;
            public string Password;
        }
        private void OnBOnDoWork(object o, DoWorkEventArgs args) { this.BackgroundWorkerDoWorkLogin(o, args); }
        private void OnBOnRunWorkerCompleted(object o, RunWorkerCompletedEventArgs args) { this.BackgroundWorkerDoWorkLoginComplete(o, args); }
        private void MethodLockUi(bool v){
            imageComboBoxEdit1.Properties.ReadOnly = v;
            textEdit1.Properties.ReadOnly = v;
            textEdit2.Properties.ReadOnly = v;
              btnlogin.Enabled = !v;
            
        }

        private void BackgroundWorkerDoWorkLogin( object sender,  DoWorkEventArgs e){
            LoginParam loginParam = (LoginParam) e.Argument;

            EntityCollection ec = new EntityCollection(new MECPSDB.FactoryClasses.SystemuserEntityFactory());
            IRelationPredicateBucket filterBucket = new RelationPredicateBucket();
            filterBucket.PredicateExpression.AddWithAnd(SystemuserFields.UserCode == loginParam.Usercode);
            filterBucket.PredicateExpression.AddWithAnd(SystemuserFields.Password == loginParam.Password);
            SystemuserEntity s = new SystemuserEntity();
        
            using (DataAccessAdapter dataAccessAdapter = new DataAccessAdapter(loginParam.Cs)){
            dataAccessAdapter.OpenConnection();
                dataAccessAdapter.FetchEntityCollection(ec,filterBucket);
            }
            e.Result = ec.Count == 1 ? ec[0] : null;

        }

        private void BackgroundWorkerDoWorkLoginComplete( object sender,  RunWorkerCompletedEventArgs e ){
            try{
                if (e.Cancelled){
                    btnlogin.Text = "Sign in";
                    pictureEdit2.Image = null;
                    MethodLockUi(false);
                    return;
                }
                if (e.Error != null){
                    AskUser.PopupSystemError(ErrorHandler.GetUserMessage(e.Error));
                    pictureEdit2.Image = null;
                    btnlogin.Text = "Sign in";
                    MethodLockUi(false);
                    return;
                }
                if (e.Result == null){
                    btnlogin.Text = "Sign in";
                    pictureEdit2.Image = null;
                    MethodLockUi(false);
                    AskUser.PopupValidationError("Invalid Sign in account.");
                    textEdit1.Focus();
                    return;
                }
                SystemUserEntity =  (SystemuserEntity) EntityOps.Clone(e.Result);

                if (SystemUserEntity.IsInactive){
                    AskUser.PopupConfirmationMessage("Sorry. But you account has been disabled.", "Validation.");
                    Close();
                    return;

                }

                if (SystemUserEntity.Rcpnl){
                    AskUser.PopupConfirmationMessage("You have been required to change your password to continue use the system.", "ADMINISTRATOR");
                    DialogChangePassword changePassword = new DialogChangePassword((string) imageComboBoxEdit1.EditValue, SystemUserEntity);
                    if (!changePassword.Showme()){
                        AskUser.PopupConfirmationMessage("Password change was not successful. \n Please re-run the application and try again.");
                        Close();
                        return;
                    }
                }
                btnlogin.Text = "Signed in";
                pictureEdit2.Image = Properties.Resources.accept;
                DialogResult = DialogResult.OK;
                Cs = (string) imageComboBoxEdit1.EditValue;
                UserCode = textEdit1.Text;
                UserCode = SystemUserEntity.UserCode;
                Close();
                return;

            } catch (Exception ex){
                AskUser.PopupSystemError(ex.Message);}
            
            }

        private void SimpleButton1Click(object sender,EventArgs e) {
            try{
                Close();
            } catch (Exception ex){
                MessageBox.Show(ex.Message);
            }
        }

        //Database=MECPGDBDEV;Server=127.0.0.1;Port=5432;User Id=postgres;Password=pangit13;SSL=True;Sslmode=Prefer;Encoding=ASCII;Protocol=3



        } //end class
    } // end namespace
